<?php
/**
 * @author spenceryg
 * @date 2023/4/25
 * @time 12:28 下午
 * @focus love & life
 */


namespace app\admin\controller;


use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Replace extends Admin
{
    public function index()
    {
        $listRows=Request::param("listRow")?Request::param("listRow"):20;//每页显示多少条
        $data=Db::name('replace')->order("sort asc")->paginate(['list_rows'=>$listRows,'query' => request()->param()]);
        // 获取分页显示
        $pagelist = $data->render();
        View::assign("pagelist",$pagelist);
        View::assign('data', $data);
        return View::fetch();
    }


    public function add()
    {
        if(request()->post()){
            $data = input();
            try{
                validate([
                    'name|关键词' => 'require|unique:replace',
                    'url|链接网址' => 'require'
                ])->check($data);
            }catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            Db::name('replace')->insert($data);
            $this->success();
        }else{
            return View::fetch();
        }
    }


    public function update()
    {
        if(request()->post()){
            $data = input();
            try{
                validate([
                    'name|关键词' => 'require|unique:replace',
                    'url|链接网址' => 'require'
                ])->check($data);
            }catch (ValidateException $e) {
                $this->error($e->getMessage());
            }
            Db::name('replace')->save($data);
            $this->success();
        }else{
            $id = input('id');
            $r = Db::name('replace')->find($id);
            View::assign('r', $r);
            return View::fetch();
        }
    }

    public function delete()
    {
        $id = input('id');
        Db::name('replace')->where('id', $id)->delete();
        $this->success();
    }





    //字段排序
    public function updateSort(){
        $ids=Request::param("id");
        $sort=Request::param("sort");
        foreach($ids as $key=>$id){
            $data['id']=(int)$id;
            $data['sort']=(int)$sort[$key];
            Db::name('replace')->save($data);
        }
        $this->success("排序更改成功");
    }
}
